package cn.net.sinodata.system.service.impl;

import cn.net.sinodata.common.core.exception.ServiceException;
import cn.net.sinodata.common.core.utils.MapstructUtils;
import cn.net.sinodata.common.core.utils.StringUtils;
import cn.net.sinodata.common.mybatis.core.page.TableDataInfo;
import cn.net.sinodata.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import cn.net.sinodata.system.domain.bo.PmHolidayDescriptionBo;
import cn.net.sinodata.system.domain.vo.PmHolidayDescriptionVo;
import cn.net.sinodata.system.domain.PmHolidayDescription;
import cn.net.sinodata.system.mapper.PmHolidayDescriptionMapper;
import cn.net.sinodata.system.service.IPmHolidayDescriptionService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 节假日描述Service业务层处理
 *
 * @author chenbaijun
 * @date 2025-11-04
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PmHolidayDescriptionServiceImpl implements IPmHolidayDescriptionService {

    private final PmHolidayDescriptionMapper baseMapper;

    /**
     * 查询节假日描述
     *
     * @param id 主键
     * @return 节假日描述
     */
    @Override
    public PmHolidayDescriptionVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询节假日描述列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 节假日描述分页列表
     */
    @Override
    public TableDataInfo<PmHolidayDescriptionVo> queryPageList(PmHolidayDescriptionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PmHolidayDescription> lqw = buildQueryWrapper(bo);
        Page<PmHolidayDescriptionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的节假日描述列表
     *
     * @param bo 查询条件
     * @return 节假日描述列表
     */
    @Override
    public List<PmHolidayDescriptionVo> queryList(PmHolidayDescriptionBo bo) {
        LambdaQueryWrapper<PmHolidayDescription> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PmHolidayDescription> buildQueryWrapper(PmHolidayDescriptionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PmHolidayDescription> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(PmHolidayDescription::getId);
        lqw.eq(bo.getHolidayDate() != null, PmHolidayDescription::getHolidayDate, bo.getHolidayDate());
        lqw.eq(StringUtils.isNotBlank(bo.getCurrencyCode()), PmHolidayDescription::getCurrencyCode, bo.getCurrencyCode());
        lqw.eq(StringUtils.isNotBlank(bo.getHolidayType()), PmHolidayDescription::getHolidayType, bo.getHolidayType());
        return lqw;
    }

    /**
     * 新增节假日描述
     *
     * @param bo 节假日描述
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(PmHolidayDescriptionBo bo) {
        validEntityBeforeSave(bo);
        PmHolidayDescription add = MapstructUtils.convert(bo, PmHolidayDescription.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 保存前的数据校验（新增时重点校验 holidayDate + currencyCode 唯一）
     * @param bo 节假日描述
     * @Author: liuzhikun
     */
    private void validEntityBeforeSave(PmHolidayDescriptionBo bo) {
        // 1. 基础非空校验
        if (bo.getHolidayDate() == null) {
            throw new ServiceException("节假日日期不能为空");
        }
        if (StringUtils.isBlank(bo.getCurrencyCode())) {
            throw new ServiceException("币种编码不能为空");
        }

        // 2. 核心校验：holidayDate 和 currencyCode 不能同时相同（新增时）
        // 构建查询条件：日期和币种同时匹配
        LambdaQueryWrapper<PmHolidayDescription> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmHolidayDescription::getHolidayDate, bo.getHolidayDate());
        lqw.eq(PmHolidayDescription::getCurrencyCode, bo.getCurrencyCode());

        // 新增操作时，id 为空，直接校验是否存在重复记录
        // 修改操作时，排除当前记录自身（避免更新时和自己冲突）
        if (StringUtils.isNotBlank(bo.getId())) {
            lqw.ne(PmHolidayDescription::getId, bo.getId());
        }

        // 执行查询，判断是否存在重复记录
        long count = baseMapper.selectCount(lqw);
        if (count > 0) {
            // 抛出业务异常，提示重复（需自定义 BusinessException）
            throw new ServiceException(String.format(
                "该日期【%s】的币种【%s】已存在节假日配置，请更换日期或币种",
                bo.getHolidayDate(), bo.getCurrencyCode()
            ));
        }
    }
    /**
     * 修改节假日描述
     *
     * @param bo 节假日描述
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(PmHolidayDescriptionBo bo) {
        validEntityBeforeSave(bo);
        PmHolidayDescription update = MapstructUtils.convert(bo, PmHolidayDescription.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PmHolidayDescription entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除节假日描述信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

}
